<?php
namespace app\blog\controller;
use think\Db;

class User extends Base
{
    public function userInfo() {
        $login = input('post.login');
        try {
            $where = [
                ['id','=',$this->userinfo['uid']]
            ];
            $exist = Db::table('mp_mix_user')->where($where)->find();
            if($login === 'login') {
                $location = $this->getLocation();
                $update_data = [
                    'ip' => $location['ip'],
                    'province' => $location['province']
                ];
                Db::table('mp_mix_token')->where('token','=',$this->userinfo['token'])->update($update_data);
                Db::table('mp_mix_user')->where($where)->update(['last_login_province'=>$location['province']]);
            }
        } catch (\Exception $e) {
            return ajax($e->getMessage(),-1);
        }
        $exist['token'] = $this->userinfo['token'];
        return ajax($exist);

    }


    //高德地图获取地理位置
    private function getLocation() {
        $ip = $this->getip();
        $parameters = [
            'key' => '3a69bef99855dc5d7e80809e59111a4b',
            'ip' => $ip,
        ];
        $url = 'https://restapi.amap.com/v3/ip?'.http_build_query($parameters);
        $res = curl_get_data($url);
        $res = json_decode($res,true);
        $res['ip'] = $ip;
        return $res;
    }

    private function getip() {
        $unknown = 'unknown';
        if ( isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown) ) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif ( isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown) ) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        /*
        处理多层代理的情况
        或者使用正则方式：$ip = preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : $unknown;
        */
        if (false !== strpos($ip, ',')) {
            $ip_arr = explode(',', $ip);
            $ip = reset($ip_arr);
        }
        return $ip;
    }

    private function asyn_email_send($data) {
        $host = $_SERVER['HTTP_HOST'];
        $param = http_build_query($data);
        $fp = @fsockopen('ssl://' . $host, 443, $errno, $errstr, 20);
        if (!$fp){
            mylog($this->cmd,'error fsockopen','fsockopen.log');
        }else{
            stream_set_blocking($fp,0);
            $http = "GET /manage/email/accountWarning?".$param." HTTP/1.1\r\n";
            $http .= "Host: ". $host ."\r\n";
            $http .= "Connection: Close\r\n\r\n";
            fwrite($fp,$http);
            usleep(1000);
            fclose($fp);
        }

    }

}